<template>
  <div class="data-table-page">
    <NavBar title="数据表格" :show-home-button="true">
      <template #right>
        <van-icon name="search" size="20" @click="showSearch = !showSearch" />
      </template>
    </NavBar>
    
    <div class="page-container">
      <!-- 搜索栏 -->
      <van-collapse-item v-model:show="showSearch" class="search-section">
        <van-search
          v-model="searchValue"
          placeholder="搜索用户名、邮箱或手机号"
          @search="handleSearch"
          @clear="handleClear"
        />
      </van-collapse-item>

      <!-- 数据统计 -->
      <div class="stats-bar card">
        <div class="stat-item">
          <span class="stat-label">总数据</span>
          <span class="stat-value">{{ totalCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">今日新增</span>
          <span class="stat-value text-success">{{ todayCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">活跃用户</span>
          <span class="stat-value text-primary">{{ activeCount }}</span>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-bar card">
        <van-dropdown-menu>
          <van-dropdown-item
            v-model="filterStatus"
            :options="statusOptions"
            @change="handleFilterChange"
          />
          <van-dropdown-item
            v-model="filterType"
            :options="typeOptions"
            @change="handleFilterChange"
          />
          <van-dropdown-item
            v-model="sortBy"
            :options="sortOptions"
            @change="handleSortChange"
          />
        </van-dropdown-menu>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <div v-if="loading" class="loading-container">
          <van-loading type="spinner" size="24px">加载中...</van-loading>
        </div>
        <div v-else-if="filteredTableData.length === 0" class="empty-container">
          <van-empty description="暂无数据" />
        </div>
        <div v-else class="table-list">
          <div
            v-for="item in paginatedData"
            :key="item.id"
            class="table-row card"
            @click="viewDetail(item)"
          >
            <div class="row-header">
              <div class="user-info">
                <van-image
                  :src="item.avatar"
                  width="40"
                  height="40"
                  round
                  fit="cover"
                  :error-icon="'user-o'"
                />
                <div class="user-details">
                  <div class="user-name">{{ item.name }}</div>
                  <div class="user-email">{{ item.email }}</div>
                </div>
              </div>
              <div class="row-actions">
                <van-tag
                  :type="getStatusType(item.status)"
                  size="small"
                >
                  {{ getStatusText(item.status) }}
                </van-tag>
              </div>
            </div>
            <div class="row-content">
              <div class="info-item">
                <span class="info-label">手机号:</span>
                <span class="info-value">{{ item.phone }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">注册时间:</span>
                <span class="info-value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">登录次数:</span>
                <span class="info-value">{{ item.loginCount }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">积分余额:</span>
                <span class="info-value text-primary">{{ item.points }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-section">
          <van-pagination
            v-model="currentPage"
            :total-items="filteredTableData.length"
            :items-per-page="pageSize"
            :show-page-size="3"
            @change="handlePageChange"
          />
        </div>
      </div>

      <!-- 导出按钮 -->
      <div class="export-section">
        <van-button
          type="primary"
          block
          round
          icon="download"
          @click="exportData"
        >
          导出数据
        </van-button>
      </div>
    </div>

    <TabBar />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'
import dayjs from 'dayjs'
import NavBar from '@/components/NavBar.vue'
import TabBar from '@/components/TabBar.vue'

interface TableItem {
  id: string
  name: string
  email: string
  phone: string
  avatar: string
  status: 'active' | 'inactive' | 'banned'
  type: 'normal' | 'vip' | 'premium'
  createTime: string
  loginCount: number
  points: number
}

// 响应式数据
const loading = ref(false)
const showSearch = ref(false)
const searchValue = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选条件
const filterStatus = ref('')
const filterType = ref('')
const sortBy = ref('createTime')

// 表格数据
const tableData = ref<TableItem[]>([])

// 筛选选项
const statusOptions = [
  { text: '全部状态', value: '' },
  { text: '活跃', value: 'active' },
  { text: '非活跃', value: 'inactive' },
  { text: '已封禁', value: 'banned' }
]

const typeOptions = [
  { text: '全部类型', value: '' },
  { text: '普通用户', value: 'normal' },
  { text: 'VIP用户', value: 'vip' },
  { text: '高级用户', value: 'premium' }
]

const sortOptions = [
  { text: '注册时间', value: 'createTime' },
  { text: '登录次数', value: 'loginCount' },
  { text: '积分余额', value: 'points' }
]

// 统计数据
const totalCount = computed(() => tableData.value.length)
const todayCount = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return tableData.value.filter(item => 
    dayjs(item.createTime).format('YYYY-MM-DD') === today
  ).length
})
const activeCount = computed(() => 
  tableData.value.filter(item => item.status === 'active').length
)

// 过滤后的数据
const filteredTableData = computed(() => {
  let data = tableData.value

  // 搜索过滤
  if (searchValue.value) {
    const keyword = searchValue.value.toLowerCase()
    data = data.filter(item =>
      item.name.toLowerCase().includes(keyword) ||
      item.email.toLowerCase().includes(keyword) ||
      item.phone.includes(keyword)
    )
  }

  // 状态过滤
  if (filterStatus.value) {
    data = data.filter(item => item.status === filterStatus.value)
  }

  // 类型过滤
  if (filterType.value) {
    data = data.filter(item => item.type === filterType.value)
  }

  // 排序
  if (sortBy.value) {
    data.sort((a, b) => {
      switch (sortBy.value) {
        case 'createTime':
          return dayjs(b.createTime).valueOf() - dayjs(a.createTime).valueOf()
        case 'loginCount':
          return b.loginCount - a.loginCount
        case 'points':
          return b.points - a.points
        default:
          return 0
      }
    })
  }

  return data
})

// 分页数据
const totalPages = computed(() => Math.ceil(filteredTableData.value.length / pageSize.value))
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTableData.value.slice(start, end)
})

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'inactive':
      return 'warning'
    case 'banned':
      return 'danger'
    default:
      return 'default'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '活跃'
    case 'inactive':
      return '非活跃'
    case 'banned':
      return '已封禁'
    default:
      return '未知'
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
}

// 处理搜索
const handleSearch = (value: string) => {
  searchValue.value = value
  currentPage.value = 1
}

// 清除搜索
const handleClear = () => {
  searchValue.value = ''
  currentPage.value = 1
}

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1
}

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 查看详情
const viewDetail = (item: TableItem) => {
  showToast(`查看用户: ${item.name}`)
  // 这里可以跳转到详情页面
}

// 导出数据
const exportData = () => {
  showToast('导出功能开发中...')
  // 这里可以实现数据导出功能
}

// 生成模拟数据
const generateMockData = (): TableItem[] => {
  const mockData: TableItem[] = []
  const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const domains = ['gmail.com', '163.com', 'qq.com', 'hotmail.com']
  const statuses: ('active' | 'inactive' | 'banned')[] = ['active', 'inactive', 'banned']
  const types: ('normal' | 'vip' | 'premium')[] = ['normal', 'vip', 'premium']

  for (let i = 0; i < 50; i++) {
    const name = names[Math.floor(Math.random() * names.length)] + i
    const email = `user${i}@${domains[Math.floor(Math.random() * domains.length)]}`
    const phone = `1${Math.floor(Math.random() * 9000000000) + 1000000000}`
    
    mockData.push({
      id: (i + 1).toString(),
      name,
      email,
      phone,
      avatar: `https://picsum.photos/40/40?random=${i}`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      type: types[Math.floor(Math.random() * types.length)],
      createTime: dayjs().subtract(Math.floor(Math.random() * 365), 'day').toISOString(),
      loginCount: Math.floor(Math.random() * 1000),
      points: Math.floor(Math.random() * 10000)
    })
  }

  return mockData
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    tableData.value = generateMockData()
  } catch (error) {
    console.error('加载数据失败:', error)
    showToast('加载数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.data-table-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.search-section {
  margin-bottom: 10px;
}

.stats-bar {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  margin-bottom: 10px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.text-success {
  color: #52c41a !important;
}

.text-primary {
  color: #1890ff !important;
}

.filter-bar {
  margin-bottom: 10px;
  padding: 0;
}

.table-section {
  min-height: 400px;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.table-row {
  margin-bottom: 10px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.table-row:active {
  background-color: #f5f5f5;
}

.row-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.user-email {
  font-size: 12px;
  color: #666;
}

.row-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 12px;
  color: #666;
}

.info-value {
  font-size: 12px;
  color: #333;
  font-weight: 500;
}

.pagination-section {
  padding: 20px;
  text-align: center;
}

.export-section {
  padding: 20px 10px;
}

:deep(.van-collapse-item__content) {
  padding: 10px;
}

:deep(.van-dropdown-menu) {
  box-shadow: none;
}

:deep(.van-dropdown-menu__bar) {
  height: 44px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>